<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 员工列表 -->
      <el-card class="box-card">
        <!-- :data="tableData" -->
        <el-table
          style="width: 100%"
          :data="employeeInfo"
          :default-sort="{prop:'mobile',order:'descending'}"
        >
          <el-table-column prop="date" label="序号" width="60" type="index" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像" width="110">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" class="staffPhoto"> -->

              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" width="110" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" :formatter="formatter" label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>

          </el-table-column>
          <el-table-column prop="correctionTime" label="转正时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>

          </el-table-column>
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="setRole(scope.row.id)"
              >分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployeeFn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          style="margin-top:10px; "
          :current-page="1"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 子组件弹框 -->
        <el-dialog
          title="新增员工"
          :visible.sync="showDialog"
          width="90%"
          @close="closeDialogFn"
        >
          <emp-dialog
            ref="addForm"
            @close="showDialog=false"
            @addEmployee="addEmployeeFn"
          >1</emp-dialog>
        </el-dialog>

        <!-- 新增角色弹框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoleDialog"
          @close="cancleDialog"
        >
          <assign-role
            v-if="showRoleDialog"
            :pession-id="pessionId"
            @close="showRoleDialog=false"
          />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入枚举(格式化后端1,2转成正式和非正式)
import EmployeeEnmu from '@/constant/employees'
import { getEmployeeList, delEmployee } from '@/api/exployee'
// 引入子组件
import EmpDialog from './empDialog'
import AssignRole from './assignRole'
// 引入dayjs
import dayjs from 'dayjs'
export default {

  filters: {
    formatTime(value) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10// 每页条数
      },
      employeeInfo: [], // 接收员工信息
      total: 0, // 总条数
      showDialog: false, // 弹框状态
      showRoleDialog: false, // 角色权限状态
      pessionId: ''// 传递给子组件的id
    }
  },

  created() {
    // 调用员工列表信息方法
    this.getEmployeeListFn()
  },
  methods: {

    setRole(id) {
      this.pessionId = id// 将id传过来
      this.showRoleDialog = true// 弹框展开
    },
    // 子组件分配好角色后,父级关闭弹框
    cancleDialog() {
      this.showRoleDialog = false
    },
    // 处理excel表格数据,将中文键值转成英文
    transData(rows) {
      // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const headerArr = Object.keys(rows[0])
      const header = headerArr.map(item => {
        return map[item]
      })
      const data = rows.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    },
    // 导出excel
    async  downloadExcel() {
      const res = await getEmployeeList(this.query)
      console.log(res)
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象

        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 添加员工的时候添加完清空表单数据
    closeDialogFn() {
      this.$refs.addForm.resetForm()
    },

    // 子组件添加员工了
    addEmployeeFn() {
      this.getEmployeeListFn()// 刷新列表
      this.showDialog = false
    },
    // 删除员工
    delEmployeeFn(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        // console.log(res)
        // 当前页面剩一条数据,就自动往前走一页
        if (this.employeeInfo.length === 1) {
          this.query.page--
        }
        // 当前页面没有内容,默认第一页
        if (this.employeeInfo.length <= 0) {
          this.query.page = 1
        }
        this.getEmployeeListFn()// 刷新员工列表

        this.$message.success(res.message)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 用来格式化内容
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnmu.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 获取员工列表
    async getEmployeeListFn() {
      const res = await getEmployeeList(this.query)
      // console.log(res)
      this.employeeInfo = res.data.rows
      this.total = res.data.total
    },
    // 处理页数问题
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeListFn()// 刷新列表
    },
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeListFn()// 刷新列表
    }
  }

}
</script>

   <style lang="scss" scoped>
   .staffPhoto {
     width: 100px;
     height: 100px;
     border-radius: 50%;
   }
   </style>

